import asyncio
import os
import time

import numpy as np
import sounddevice as sd
from mcp_tool import mcp_tool_func

from xiaozhi_sdk import XiaoZhiWebsocket
from xiaozhi_sdk.utils import read_audio_file

MAC_ADDR = "00:22:44:66:88:00"
sample_rate = 16000
frame_duration = 60

current_dir = os.path.dirname(os.path.abspath(__file__))


# 创建一个持续播放的流
async def assistant_audio_play(audio_queue):
    stream = sd.OutputStream(samplerate=sample_rate, channels=1, dtype=np.int16)
    stream.start()
    last_time = None
    while True:
        if not audio_queue:
            await asyncio.sleep(0.01)
            if last_time and time.time() - last_time > 1:
                break
            continue

        pcm_data = audio_queue.popleft()
        stream.write(pcm_data)
        last_time = time.time()

    stream.stop()
    stream.close()


async def message_handler_callback(message):
    print("message received:", message)


async def main():
    xiaozhi = XiaoZhiWebsocket(
        message_handler_callback, audio_sample_rate=sample_rate, audio_frame_duration=frame_duration
    )
    await xiaozhi.set_mcp_tool(mcp_tool_func(xiaozhi))
    await xiaozhi.init_connection(MAC_ADDR)

    # say hellow
    for pcm in read_audio_file(
        f"{current_dir}/../xiaozhi_sdk/file/audio/16k_say_hello.wav", sample_rate, frame_duration
    ):
        await xiaozhi.send_audio(pcm)
    await xiaozhi.send_silence_audio()
    await assistant_audio_play(xiaozhi.output_audio_queue)

    # say take photo
    for pcm in read_audio_file(
        f"{current_dir}/../xiaozhi_sdk/file/audio/16k_take_photo.wav", sample_rate, frame_duration
    ):
        await xiaozhi.send_audio(pcm)
    await xiaozhi.send_silence_audio()
    await assistant_audio_play(xiaozhi.output_audio_queue)

    await xiaozhi.close()


if __name__ == "__main__":
    asyncio.run(main())
